package mark.tom.gear.base.app

import android.app.Application
import android.content.Context
import android.os.Build
import android.os.StrictMode
import android.webkit.WebView
import androidx.annotation.CallSuper
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import mark.tom.fiter.Buz
import mark.tom.fiter.GsonDataResolver
import mark.tom.fiter.HttpRequestManager
import mark.tom.fiter.ResolverFactory
import mark.tom.fiter.bean.config.OkHttpConfig
import mark.tom.fiter.http.ssl.NoneSSLSocketFactory
import mark.tom.gear.base.interceptor.RecordInterceptor
import mark.tom.gear.base.utils.GmuUtil
import mark.tom.gear.base.utils.LogUtil
import mark.tom.gear.base.utils.RouterUtil
import mark.tom.gear.base.utils.ToastUtil
import okhttp3.logging.HttpLoggingInterceptor

/**
 * @Description: Application基类
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.app.base
 * @Date: 2020/12/31
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
abstract class BaseApplication : Application() {

    @CallSuper
    override fun onCreate() {
        super.onCreate()
        // 注册app生命回调监听
        registerActivityLifecycleCallbacks(BaseActivityLifecycleCallback())
        // init Log
        if (isApplicationDebuggable()) {
            // Enable Strict Mode
            enabledStrictMode()
            // 初始化日志工具
            LogUtil.init()
            // 打开GMU的debug开关
            GmuUtil.openDebug()
            // 打开路由的debug开关
            RouterUtil.openDebug()
        }
        // 初始化Toast
        ToastUtil.initialize(this)
        // 初始化网络请求管理器
        initHttpRequestManager(isApplicationDebuggable(), this)
        // 初始化路由框架
        RouterUtil.init(this)
        // 初始化GMU混合内核
        GmuUtil.initHybridCore(this)
        // Init 崩溃日志服务
        GmuUtil.initCrashService(this)
        // Init WebView Suffix
        initWebViewSuffix()
    }

    /**
     * Description: 使用严格模式
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/13 4:24 下午
     */
    private fun enabledStrictMode() {
        StrictMode.setThreadPolicy(
            StrictMode.ThreadPolicy.Builder()
                .detectCustomSlowCalls()
                .detectNetwork()
                .penaltyDialog()
                .penaltyLog()
                .penaltyFlashScreen()
                .build()
        )
        // 解决Android 7.0系统拍照问题
        val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure()
        }
        builder.detectLeakedSqlLiteObjects()
            .penaltyLog()
            .penaltyDeath()
        StrictMode.setVmPolicy(builder.build())
    }

    /**
     * Description: 初始化WebView后缀
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/15 10:35 上午
     */
    private fun initWebViewSuffix() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            return
        }
        val processName = getProcessName()
        // 判断不等于默认进程名称
        if (packageName != processName) {
            WebView.setDataDirectorySuffix(processName)
        }
    }

    /**
     * Description: 初始化Http请求管理器
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/2/8 2:43 下午
     */
    private fun initHttpRequestManager(debuggable: Boolean, mContext: Context) {
        HttpRequestManager.initHttpConfig(
            Buz.Builder()
                .okHttpConfig(
                    // 设置OkHttp配置信息
                    OkHttpConfig()
                        .setUseProxy(debuggable)
                        .setCookieJar(PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(mContext)))
                        .addRequestInterceptors(HttpLoggingInterceptor {
                            LogUtil.d(it)
                        }.setLevel(HttpLoggingInterceptor.Level.BODY))
                        .addRequestInterceptors(RecordInterceptor(object : RecordInterceptor.Recorder {
                            override fun record(method: String?, url: String?, exception: Boolean, tookMs: Long) {
                                LogUtil.d("url -> %s \n method -> %s \n tookMs -> %s \n exception -> %s", url, method, tookMs, exception)
                            }
                        }))
                        .setSslSocketFactory(NoneSSLSocketFactory.getHttpSSLSocketFactory())
                )
                // 加载Gson数据解析器
                .resolver(ResolverFactory().get(GsonDataResolver()))
                .build()
        )
    }

    /**
     * Description: 判断Application是否可以debug
     * Copyright: Copyright (c) 2021
     * Project: Gear
     * Author: ttmk110@163.com
     * Date: 2021/1/14 10:46 上午
     */
    abstract fun isApplicationDebuggable(): Boolean
}